package com.example.minilark.presentation.contacts

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.minilark.data.model.Contact
import com.example.minilark.databinding.ItemContactBinding
import coil.load
import coil.transform.CircleCropTransformation
import android.util.Log
import coil.request.CachePolicy
import android.widget.ImageView
import android.graphics.drawable.ColorDrawable
import android.graphics.Color
import coil.ImageLoader
import coil.decode.DataSource
import coil.request.ImageRequest
import okhttp3.OkHttpClient
import java.util.concurrent.TimeUnit
import android.content.Context

class ContactsAdapter(
    context: Context,
    private val onItemClick: (Contact) -> Unit
) : ListAdapter<Contact, ContactsAdapter.ContactViewHolder>(ContactDiffCallback()) {

    private val imageLoader = ImageLoader.Builder(context)
        .crossfade(true)
        .okHttpClient {
            OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .followRedirects(true)
                .followSslRedirects(true)
                .retryOnConnectionFailure(true)
                .build()
        }
        .build()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ContactViewHolder {
        val binding = ItemContactBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
        return ContactViewHolder(binding)
    }

    override fun onBindViewHolder(holder: ContactViewHolder, position: Int) {
        val contact = getItem(position)
        holder.bind(contact)
    }

    inner class ContactViewHolder(
        private val binding: ItemContactBinding
    ) : RecyclerView.ViewHolder(binding.root) {

        init {
            binding.root.setOnClickListener {
                val position = layoutPosition
                if (position != RecyclerView.NO_POSITION) {
                    onItemClick(getItem(position))
                }
            }
        }

        fun bind(contact: Contact) {
            binding.userName.text = contact.username
            
            // 设置ImageView的缩放类型
            binding.userAvatar.scaleType = ImageView.ScaleType.CENTER_CROP
            
            // 使用 Coil 加载头像
            Log.d("ContactsAdapter", "Loading avatar for ${contact.username}: ${contact.profilePicture}")
            
            val request = ImageRequest.Builder(binding.root.context)
                .data(contact.profilePicture)
                .target(binding.userAvatar)
                .placeholder(ColorDrawable(Color.LTGRAY))
                .error(android.R.drawable.ic_menu_gallery)
                .transformations(CircleCropTransformation())
                .memoryCachePolicy(CachePolicy.DISABLED)
                .diskCachePolicy(CachePolicy.DISABLED)
                .listener(
                    onStart = {
                        Log.d("ContactsAdapter", "Started loading avatar for ${contact.username} from URL: ${contact.profilePicture}")
                    },
                    onSuccess = { _, result ->
                        Log.d("ContactsAdapter", "Successfully loaded avatar for ${contact.username} from URL: ${contact.profilePicture}")
                        Log.d("ContactsAdapter", "Image size: ${result.drawable.intrinsicWidth}x${result.drawable.intrinsicHeight}")
                        Log.d("ContactsAdapter", "Source: ${result.dataSource}")
                    },
                    onError = { _, error ->
                        Log.e("ContactsAdapter", "Failed to load avatar for ${contact.username} from URL: ${contact.profilePicture}")
                        Log.e("ContactsAdapter", "Error details: ${error.throwable}")
                        error.throwable.printStackTrace()
                    }
                )
                .build()
            
            imageLoader.enqueue(request)
        }
    }

    private class ContactDiffCallback : DiffUtil.ItemCallback<Contact>() {
        override fun areItemsTheSame(oldItem: Contact, newItem: Contact): Boolean {
            return oldItem.username == newItem.username
        }

        override fun areContentsTheSame(oldItem: Contact, newItem: Contact): Boolean {
            return oldItem.username == newItem.username &&
                   oldItem.profilePicture == newItem.profilePicture
        }
    }
} 